package me.leiusual.sharing.ui.product

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.bumptech.glide.load.resource.bitmap.FitCenter
import com.youth.banner.loader.ImageLoader
import kotlinx.android.synthetic.main.fragment_product_detail.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.ApiSharing
import me.leiusual.sharing.api.model.ProductDetail
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.MainViewModel
import me.leiusual.sharing.ui.base.AbstractWebViewFragment
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.product.dialog.ProductOptionalDialog
import me.leiusual.sharing.util.extension.setImageUrl
import me.leiusual.sharing.util.extension.spToPx
import me.leiusual.sharing.util.extension.toSpanned
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-26
 * description:
 */
class ProductDetailFragment : AbstractWebViewFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val mainViewModel: MainViewModel by activityViewModels { factory }

  private val viewModel: ProductDetailViewModel by viewModels { factory }

  private val args: ProductDetailFragmentArgs by navArgs()

  override val layoutWebView: LinearLayout
    get() = layout_web_view

  private val imageLoader = object : ImageLoader() {
    override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
      imageView?.setImageUrl(path) { it.transform(FitCenter()) }
    }
  }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_product_detail, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }
    toolbar.setOnMenuItemClickListener {
      Timber.v("menuItem = %s, itemId = %s, groupId = %s", it, it.itemId, it.groupId)
      if (it.groupId == 1) {
        viewModel.productDetail(it.itemId.toLong(), args.mid, args.r)
        true
      } else {
        false
      }
    }

    button_store.setOnClickListener(this)
    button_cart.setOnClickListener(this)
    button_add_to_cart.setOnClickListener(this)

    observeData()
    viewModel.productDetail(null, args.mid, args.r)
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.button_store -> {
        val data = viewModel.productDetail.value as? Data.Success
        data?.data?.store?.id?.let {
          val navDirections = ProductDetailFragmentDirections.actionProductDetailFragmentToStoreHomeFragment(it)
          findNavController().navigate(navDirections)
        }
      }
      R.id.button_cart -> {
        findNavController().navigate(R.id.action_productDetailFragment_to_cartHomeFragment)
      }
      R.id.button_add_to_cart -> {
        ProductOptionalDialog().showNow(childFragmentManager, ProductOptionalDialog::class.simpleName)
      }
    }
  }

  private fun observeData() {
    viewModel.productDetail.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("productDetail = %s", it)
      when (it) {
        is Data.Loading -> {
          state_constraint_layout.showProgress()
        }
        is Data.Error -> {
          state_constraint_layout.showError(it.error.message)
        }
        is Data.Success -> {
          state_constraint_layout.showContent()

          // 临存
          mainViewModel.productDetail(it.data)

          // 更新界面
          updateViews(it.data)
        }
      }
    })
  }

  /**
   * 更新商品信息
   */
  private fun updateViews(productDetail: ProductDetail) {

    // 更新可切换按钮
    toolbar.menu.clear()
    val subMenu = toolbar.menu.addSubMenu(productDetail.storeArea.name + ">")
    subMenu.item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
    productDetail.allArea.forEach {
      subMenu.add(1, it.id, 0, it.name)
    }

    // 图片
    val images = productDetail.pictures.map { it.url }
    banner.setImages(images).setImageLoader(imageLoader).start()

    // 价格
    val sizePrice = 26f.spToPx(requireContext())
    val size = 18f.spToPx(requireContext())
    val builder = StringBuilder()
    builder.append("""<font color="red">""")
    builder.append("""￥<size_$sizePrice>${productDetail.validPrice.pointCoinString}</size_$sizePrice>""")
    if (productDetail.validPoints.pointCoin != 0.0) {
      builder.append("""   分<size_$size>${productDetail.validPoints.pointCoinString}</size_$size>""")
    }
    builder.append("""</font>""")
    if (productDetail.originPrice.toDoubleOrNull() ?: 0.0 > 0 && productDetail.originPrice != productDetail.validPrice.pointCoinString) {
      builder.append("""   <del>￥<size_$size>${productDetail.originPrice}</size_$size></del>""")
    }
    text_view_price.text = builder.toString().toSpanned()

    // 名称
    text_view_product_name.text = productDetail.productModelName

    // 参数
    text_view_params.text = StringBuilder().apply {
      if (productDetail.params.isEmpty()) {
        append("暂无信息")
      } else {
        productDetail.params.forEach {
          append(it.name)
          append(": ")
          append(it.value)
          append("\n")
        }
      }
    }

    // 详情
    val js = """<script type="text/javascript">
      var imgs = document.getElementsByTagName('img');
      for(var i = 0; i < imgs.length; i++) {
        imgs[i].style.width = '100%';
        imgs[i].style.height = 'auto';
      }
      </script>""".trimMargin()
    webView.loadDataWithBaseURL(ApiSharing.BASE_URL, productDetail.product.detail + js, "text/html", "utf-8", null)
  }
}